<template>
  <div class="project-management">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="项目名称">
          <el-input v-model="searchForm.name" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="筹备中" value="preparing" />
            <el-option label="招募中" value="recruiting" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">新增项目</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="projectList" border stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="项目名称" min-width="200">
          <template #default="{ row }">
            <div class="project-name">
              <el-image
                :src="row.image"
                :preview-src-list="[row.image]"
                fit="cover"
                class="project-cover"
              />
              <span>{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="活动时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.date) }}
          </template>
        </el-table-column>
        <el-table-column prop="location" label="活动地点" width="180" />
        <el-table-column prop="participants" label="参与人数" width="120">
          <template #default="{ row }">
            {{ row.currentParticipants }}/{{ row.maxParticipants }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getAuditStatusType(row.auditStatus)">
              {{ getAuditStatusText(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.status === 0 || row.status === 'preparing'"
              link 
              type="primary" 
              @click="handlePublish(row)"
            >发布</el-button>
            <el-button 
              v-if="row.status === 1 || row.status === 'recruiting'"
              link 
              type="warning" 
              @click="handleCloseRecruitment(row)"
            >结束招募</el-button>
            <el-button 
              v-if="row.status === 2 || row.status === 'ongoing'"
              link 
              type="success" 
              @click="handleComplete(row)"
            >完成项目</el-button>
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" @click="handleDetail(row)">详情</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 项目表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增项目' : '编辑项目'"
      width="800px"
    >
      <el-form
        ref="projectFormRef"
        :model="projectForm"
        :rules="projectRules"
        label-width="100px"
      >
        <el-form-item label="项目名称" prop="title">
          <el-input v-model="projectForm.title" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目封面" prop="image">
          <el-upload
            class="cover-uploader"
            action="http://localhost:8081/api/upload/image"
            :headers="getUploadHeaders()"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeCoverUpload"
            name="file"
          >
            <img v-if="projectForm.image" :src="projectForm.image" class="cover" />
            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="开始时间" prop="date">
          <el-date-picker
            v-model="projectForm.date"
            type="datetime"
            placeholder="选择活动开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker
            v-model="projectForm.endDate"
            type="datetime"
            placeholder="选择活动结束时间"
          />
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="projectForm.location" placeholder="请输入活动地点" />
        </el-form-item>
        <el-form-item label="详细地址" prop="fullAddress">
          <el-input v-model="projectForm.fullAddress" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="最大人数" prop="maxParticipants">
          <el-input-number
            v-model="projectForm.maxParticipants"
            :min="1"
            :max="1000"
          />
        </el-form-item>
        <el-form-item label="活动时长(分钟)" prop="duration">
          <el-input-number
            v-model="projectForm.duration"
            :min="30"
            :max="1440"
          />
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input
            v-model="projectForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入项目描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="项目详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="项目名称" :span="2">{{ currentDetail.title }}</el-descriptions-item>
        <el-descriptions-item label="项目封面" :span="2">
          <el-image
            :src="currentDetail.image"
            :preview-src-list="[currentDetail.image]"
            fit="cover"
            class="detail-cover"
          />
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ formatDate(currentDetail.date) }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ formatDate(currentDetail.endDate) }}</el-descriptions-item>
        <el-descriptions-item label="活动地点">{{ currentDetail.location }}</el-descriptions-item>
        <el-descriptions-item label="详细地址">{{ currentDetail.fullAddress }}</el-descriptions-item>
        <el-descriptions-item label="参与人数">
          {{ currentDetail.currentParticipants }}/{{ currentDetail.maxParticipants }}
        </el-descriptions-item>
        <el-descriptions-item label="活动时长">{{ currentDetail.duration }} 分钟</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentDetail.status)">
            {{ getStatusText(currentDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getAuditStatusType(currentDetail.auditStatus)">
            {{ getAuditStatusText(currentDetail.auditStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="组织者">{{ currentDetail.organizationName }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(currentDetail.createTime) }}</el-descriptions-item>
        <el-descriptions-item v-if="currentDetail.rejectReason" label="拒绝原因" :span="2">
          {{ currentDetail.rejectReason }}
        </el-descriptions-item>
        <el-descriptions-item label="项目描述" :span="2">{{ currentDetail.description }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { 
  getProjectList, 
  getProjectDetail, 
  addProject, 
  updateProject, 
  deleteProject 
} from '@/api/project'

// 搜索表单
const searchForm = reactive({
  name: '',
  status: '',
  dateRange: []
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 项目列表
const projectList = ref([])

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add')
const detailDialogVisible = ref(false)
const currentDetail = ref({})
const projectFormRef = ref(null)

// 项目表单
const projectForm = reactive({
  title: '',
  image: '',
  date: '',
  endDate: '',
  location: '',
  fullAddress: '',
  maxParticipants: 30,
  duration: 120,
  description: '',
  organizationId: 1,
  organizationName: '',
  status: 0,
  auditStatus: 0
})

// 表单校验规则
const projectRules = {
  title: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传项目封面', trigger: 'change' }
  ],
  date: [
    { required: true, message: '请选择活动时间', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  fullAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  maxParticipants: [
    { required: true, message: '请输入最大人数', trigger: 'change' }
  ],
  duration: [
    { required: true, message: '请输入活动时长', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入项目描述', trigger: 'blur' }
  ]
}

// 初始化加载数据
onMounted(() => {
  fetchProjectList()
})

// 获取项目列表数据
const fetchProjectList = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      name: searchForm.name,
      status: searchForm.status
    }
    
    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }
    
    const res = await getProjectList(params)
    projectList.value = res.data.list || []
    total.value = res.data.total || 0
  } catch (error) {
    console.error('获取项目列表失败', error)
  }
}

// 日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '暂无';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-');
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'info',     // 筹备中
    1: 'warning',  // 招募中
    2: 'primary',  // 进行中
    3: 'success',  // 已完成
    preparing: 'info',
    recruiting: 'warning',
    ongoing: 'primary',
    completed: 'success'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '筹备中',
    1: '招募中',
    2: '进行中',
    3: '已完成',
    preparing: '筹备中',
    recruiting: '招募中',
    ongoing: '进行中',
    completed: '已完成'
  }
  return texts[status] || '未知'
}

// 获取审核状态类型
const getAuditStatusType = (status) => {
  const types = {
    0: 'warning',  // 待审核
    1: 'success',  // 已通过
    2: 'danger'    // 已拒绝
  }
  return types[status] || 'info'
}

// 获取审核状态文本
const getAuditStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝'
  }
  return texts[status] || '未知'
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchProjectList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  currentPage.value = 1
  fetchProjectList()
}

// 处理新增
const handleAdd = () => {
  resetForm()
  dialogType.value = 'add'
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = async (row) => {
  try {
    // 先清空表单，避免显示上一次的数据
    resetForm()
    
    // 获取详细数据
    const res = await getProjectDetail(row.id)
    if (!res || !res.data) {
      throw new Error('获取项目详情失败，返回数据为空')
    }
    
    const projectData = res.data
    
    // 安全地设置表单值，确保每个字段都有默认值
    projectForm.id = projectData.id
    projectForm.title = projectData.title || ''
    projectForm.image = projectData.image || ''
    projectForm.date = projectData.date || ''
    projectForm.endDate = projectData.endDate || ''
    projectForm.location = projectData.location || ''
    projectForm.fullAddress = projectData.fullAddress || ''
    projectForm.maxParticipants = projectData.maxParticipants || 30
    projectForm.duration = projectData.duration || 120
    projectForm.description = projectData.description || ''
    projectForm.organizationId = projectData.organizationId || 1
    projectForm.organizationName = projectData.organizationName || ''
    projectForm.status = typeof projectData.status === 'number' ? projectData.status : 0
    projectForm.auditStatus = typeof projectData.auditStatus === 'number' ? projectData.auditStatus : 0
    
    // 设置对话框类型并显示
    dialogType.value = 'edit'
    dialogVisible.value = true
  } catch (error) {
    console.error('获取项目详情失败', error)
    ElMessage.error('获取项目详情失败：' + (error.message || '未知错误'))
  }
}

// 重置表单
const resetForm = () => {
  projectForm.id = undefined
  projectForm.title = ''
  projectForm.image = ''
  projectForm.date = ''
  projectForm.endDate = ''
  projectForm.location = ''
  projectForm.fullAddress = ''
  projectForm.maxParticipants = 30
  projectForm.duration = 120
  projectForm.description = ''
  projectForm.organizationId = 1
  projectForm.organizationName = ''
  projectForm.status = 0
  projectForm.auditStatus = 0
}

// 处理详情
const handleDetail = async (row) => {
  try {
    const res = await getProjectDetail(row.id)
    currentDetail.value = res.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取项目详情失败', error)
    ElMessage.error('获取项目详情失败')
  }
}

// 处理发布
const handlePublish = (row) => {
  ElMessageBox.confirm(
    '确认发布该项目？发布后将开始招募志愿者',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await updateProject(row.id, { status: 1 }) // 招募中
      ElMessage.success('项目已发布')
      fetchProjectList()
    } catch (error) {
      console.error('发布项目失败', error)
    }
  })
}

// 处理结束招募
const handleCloseRecruitment = (row) => {
  ElMessageBox.confirm(
    '确认结束招募？结束后将无法继续报名',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await updateProject(row.id, { status: 2 }) // 进行中
      ElMessage.success('已结束招募')
      fetchProjectList()
    } catch (error) {
      console.error('结束招募失败', error)
    }
  })
}

// 处理完成项目
const handleComplete = (row) => {
  ElMessageBox.confirm(
    '确认完成该项目？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await updateProject(row.id, { status: 3 }) // 已完成
      ElMessage.success('项目已完成')
      fetchProjectList()
    } catch (error) {
      console.error('完成项目失败', error)
    }
  })
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该项目？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteProject(row.id)
      ElMessage.success('删除成功')
      fetchProjectList()
    } catch (error) {
      console.error('删除项目失败', error)
    }
  })
}

// 处理表单提交
const handleSubmit = async () => {
  if (!projectFormRef.value) return
  
  await projectFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 日期处理，确保日期格式正确
        const submitData = {...projectForm}
        
        // 日期处理
        if (submitData.date instanceof Date) {
          submitData.date = submitData.date.toISOString()
        }
        if (submitData.endDate instanceof Date) {
          submitData.endDate = submitData.endDate.toISOString()
        }
        
        if (dialogType.value === 'add') {
          // 添加时移除ID字段
          delete submitData.id
          await addProject(submitData)
          ElMessage.success('添加成功')
        } else {
          if (!submitData.id) {
            throw new Error('缺少项目ID，无法更新')
          }
          await updateProject(submitData.id, submitData)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchProjectList()
      } catch (error) {
        console.error('提交项目失败', error)
        ElMessage.error('提交失败：' + (error.message || '未知错误'))
      }
    }
  })
}

// 处理封面上传成功
const handleCoverSuccess = (response) => {
  projectForm.image = response.data.url
  ElMessage.success('上传成功')
}

// 获取上传请求头
const getUploadHeaders = () => {
  const token = localStorage.getItem('token')
  return {
    Authorization: token ? `Bearer ${token}` : ''
  }
}

// 上传前校验
const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchProjectList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchProjectList()
}
</script>

<style scoped lang="scss">
.project-management {
  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .project-name {
    display: flex;
    align-items: center;
    gap: 12px;

    .project-cover {
      width: 60px;
      height: 40px;
      border-radius: 4px;
    }
  }

  .cover-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .cover-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 100px;
      text-align: center;
      line-height: 100px;
    }

    .cover {
      width: 178px;
      height: 100px;
      display: block;
      object-fit: cover;
    }
  }

  .detail-cover {
    width: 300px;
    height: 200px;
    border-radius: 4px;
  }
}
</style> 